<template>
	<div class="order-detail-container" v-loading="loading">
		<!-- 头部 -->
		<el-card class="mb-6">
			<div class="header-content">
				<h3 class="order-title">订单详情 - {{ orderData.orderNumber }}</h3>
				<div class="action-buttons">
					<el-button type="primary" :icon="Edit" @click="handleEdit">
						编辑订单
					</el-button>
					<el-button :icon="Switch" @click="handleStatusChange">
						{{ orderStatusActionText }}
					</el-button>
				</div>
			</div>

			<el-card shadow="never" class="mt-4">
				<div class="amount-info">
					<div class="info-item">
						<span class="info-label">订单金额</span>
						<span class="info-value price">¥{{ formattedAmount }}</span>
					</div>
					<div class="info-item">
						<span class="info-label">订单类型</span>
						<span class="info-value">
							{{ orderTypeText }}
						</span>
					</div>
				</div>
			</el-card>
		</el-card>

		<!-- Main Content -->
		<div class="main-content">
			<!-- Left Content (8 columns) -->
			<div class="left-content">
				<!-- 订单基本信息 -->
				<el-card>
					<template #header>
						<div class="card-header">
							<span>订单信息</span>
						</div>
					</template>

					<div class="order-info">
						<div class="info-row">
							<div class="info-col">
								<span class="info-label">订单 ID</span>
								<span class="info-value">{{ orderData.id }}</span>
							</div>
							<div class="info-col">
								<span class="info-label">用户 ID</span>
								<span class="info-value">{{ orderData.userId }}</span>
							</div>
						</div>

						<div class="info-row">
							<div class="info-col">
								<span class="info-label">用户手机号</span>
								<span class="info-value">{{ orderData.userPhone }}</span>
							</div>
							<div class="info-col">
								<span class="info-label">支付方式</span>
								<span class="info-value">{{ orderData.paymentMethod || '未支付' }}</span>
							</div>
						</div>

						<div class="info-row">
							<div class="info-col">
								<span class="info-label">交易单号</span>
								<span class="info-value">{{ orderData.transactionId || '无' }}</span>
							</div>
							<div class="info-col">
								<span class="info-label">订单备注</span>
								<span class="info-value">{{ orderData.remark || '无' }}</span>
							</div>
						</div>
					</div>
				</el-card>

				<!-- 订单商品/课程/包间信息 -->
				<el-card class="mt-6">
					<template #header>
						<div class="card-header">
							<span>订单内容</span>
						</div>
					</template>

					<div class="order-items">
						<el-empty v-if="!hasOrderItems" description="暂无订单内容" :image-size="100" />

						<!-- 商品信息 -->
						<div v-if="orderData.products && orderData.products.length > 0">
							<h4 class="items-title">商品信息</h4>
							<el-table :data="orderData.products" border style="width: 100%" class="mb-4">
								<el-table-column prop="title" label="商品名称" width="180">
									<template #default="{row}">
										<div class="product-info">
											<el-image v-if="row.image" :src="row.image" fit="cover"
												class="product-image" />
											<span>{{ row.title }}</span>
										</div>
									</template>
								</el-table-column>
								<el-table-column prop="specification" label="规格" width="120" />
								<el-table-column prop="price" label="单价(元)" width="120">
									<template #default="{row}">
										¥{{ row.price ? Number(row.price).toFixed(2) : '0.00' }}
									</template>
								</el-table-column>
								<el-table-column prop="quantity" label="数量" width="100" />
								<el-table-column prop="unit" label="单位" width="80" />
								<el-table-column label="小计(元)" width="120">
									<template #default="{row}">
										¥{{ row.price && row.quantity ? (Number(row.price) * row.quantity).toFixed(2) : '0.00' }}
									</template>
								</el-table-column>
								<el-table-column label="状态" width="100">
									<template #default="{row}">
										<el-tag :type="row.isOffShelf === 1 ? 'danger' : 'success'" size="small">
											{{ row.isOffShelf === 1 ? '已下架' : '在售' }}
										</el-tag>
									</template>
								</el-table-column>
							</el-table>
						</div>

						<!-- 课程信息 -->
						<div v-if="orderData.courses" class="mt-6">
							<h4 class="items-title">课程信息</h4>
							<div class="course-detail">
								<div class="course-header">
									<el-image v-if="orderData.courses.image" :src="orderData.courses.image" fit="cover"
										class="course-image" />
									<div class="course-info">
										<h5>{{ orderData.courses.title }}</h5>
										<p class="course-description">{{ orderData.courses.description }}</p>
										<div class="course-meta">
											<span class="meta-item">
												<el-icon>
													<Calendar />
												</el-icon>
												{{ formatDateTime(orderData.courses.startTime) }}
											</span>
											<span class="meta-item">
												<el-icon>
													<User />
												</el-icon>
												{{ orderData.courses.enrolledCount }}/{{ orderData.courses.peopleLimit === -1 ? '不限' : orderData.courses.peopleLimit }}
											</span>
											<span class="meta-item">
												<el-tag :type="getCourseStatusTagType(orderData.courses.status)"
													size="small">
													{{ getCourseStatusText(orderData.courses.status) }}
												</el-tag>
											</span>
										</div>
									</div>
									<div class="course-price">
										<span class="price-label">课程费用</span>
										<span
											class="price-value">¥{{ orderData.courses.fee ? Number(orderData.courses.fee).toFixed(2) : '0.00' }}</span>
									</div>
								</div>
							</div>
						</div>

						<!-- 包间信息 -->
						<div v-if="orderData.rooms" class="mt-6">
							<h4 class="items-title">包间信息</h4>
							<div class="room-detail">
								<div class="room-header">
									<el-image v-if="orderData.rooms.image" :src="orderData.rooms.image" fit="cover"
										class="room-image" />
									<div class="room-info">
										<h5>{{ orderData.rooms.roomName }}</h5>
										<p class="room-description">{{ orderData.rooms.description }}</p>
										<div class="room-meta">
											<span class="meta-item">
												<el-icon>
													<User />
												</el-icon>
												容纳人数: {{ orderData.rooms.seatingCapacity }}人
											</span>
											<span class="meta-item">
												<el-tag :type="getRoomTypeTagType(orderData.rooms.roomType)"
													size="small">
													{{ getRoomTypeText(orderData.rooms.roomType) }}
												</el-tag>
											</span>
											<span class="meta-item">
												<el-tag :type="orderData.rooms.isAvailable ? 'success' : 'danger'"
													size="small">
													{{ orderData.rooms.isAvailable ? '可用' : '不可用' }}
												</el-tag>
											</span>
										</div>
									</div>
									<div class="room-price">
										<span class="price-label">包间费用</span>
										<span
											class="price-value">¥{{ orderData.rooms.fee ? Number(orderData.rooms.fee).toFixed(2) : '0.00' }}</span>
									</div>
								</div>
							</div>
						</div>
					</div>
				</el-card>
			</div>

			<!-- 系统信息 -->
			<div class="right-sidebar">
				<el-card>
					<template #header>
						<div class="card-header">
							<span>系统信息</span>
						</div>
					</template>

					<div class="system-info">
						<div class="info-item">
							<span class="info-label">创建时间</span>
							<span class="info-value">{{ orderData.createdAt }}</span>
						</div>
						<div class="info-item">
							<span class="info-label">更新时间</span>
							<span class="info-value">{{ orderData.updatedAt }}</span>
						</div>
						<div class="info-item">
							<span class="info-label">订单状态</span>
							<el-tag :type="orderStatusTagType" size="small">
								{{ orderStatusText }}
							</el-tag>
						</div>
						<div class="info-item">
							<span class="info-label">支付状态</span>
							<el-tag :type="paymentStatusTagType" size="small">
								{{ paymentStatusText }}
							</el-tag>
						</div>
					</div>
				</el-card>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'OrderDetailView'
	};
</script>

<script setup>
	import {
		getOrderDetails,
		updateOrder,
		accomplishOrder,
		enableRefundStatus
	} from '@/api/order.js'
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		Edit,
		Switch,
		Calendar,
		User
	} from '@element-plus/icons-vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'

	const route = useRoute()
	const router = useRouter()
	const loading = ref(false)
	const orderId = ref(route.params.id)
	const orderData = ref({})

	/**
	 * 计算格式化后的金额
	 */
	const formattedAmount = computed(() => {
		return orderData.value.totalAmount ? Number(orderData.value.totalAmount).toFixed(2) : '0.00'
	})
	/**
	 * 格式化日期时间
	 */
	const formatDateTime = (dateTime) => {
		if (!dateTime) return '未设置'
		return new Date(dateTime).toLocaleString()
	}

	/**
	 * 获取课程状态标签类型
	 */
	const getCourseStatusTagType = (status) => {
		const statusTypes = {
			0: 'info', // 未开始
			1: 'success', // 已开始
			2: 'warning', // 已结束
			3: 'danger' // 已取消
		}
		return statusTypes[status] || 'info'
	}

	/**
	 * 获取课程状态文本
	 */
	const getCourseStatusText = (status) => {
		const statusTexts = {
			0: '未开始',
			1: '已开始',
			2: '已结束',
			3: '已取消'
		}
		return statusTexts[status] || '未知状态'
	}

	/**
	 * 获取包间类型标签类型
	 */
	const getRoomTypeTagType = (type) => {
		const typeTypes = {
			0: '', // 大厅
			1: 'success', // 茶室
			2: 'warning' // 包间
		}
		return typeTypes[type] || 'info'
	}

	/**
	 * 获取包间类型文本
	 */
	const getRoomTypeText = (type) => {
		const typeTexts = {
			0: '大厅',
			1: '茶室',
			2: '包间'
		}
		return typeTexts[type] || '未知类型'
	}
	/**
	 * 订单类型文本
	 */
	const orderTypeText = computed(() => {
		const types = {
			1: '商品订单',
			2: '课程订单',
			3: '包间订单',
		}
		return types[orderData.value.orderType] || '未知类型'
	})

	/**
	 * 订单状态标签类型
	 */
	const orderStatusTagType = computed(() => {
		const status = orderData.value.orderStatus
		const statusTypes = {
			0: 'info', // 待支付
			1: 'warning', // 已支付待完成
			2: 'success', // 已完成
			3: 'danger' // 已取消
		}
		return statusTypes[status] || 'info'
	})

	/**
	 * 订单状态文本
	 */
	const orderStatusText = computed(() => {
		const status = orderData.value.orderStatus
		const statusTexts = {
			0: '待支付',
			1: '已支付待完成',
			2: '已完成',
			3: '已取消'
		}
		return statusTexts[status] || '未知状态'
	})

	/**
	 * 支付状态标签类型
	 */
	const paymentStatusTagType = computed(() => {
		const status = orderData.value.paymentStatus
		const statusTypes = {
			1: 'info', // 未支付
			2: 'success', // 已支付
			3: 'danger' // 已退款
		}
		return statusTypes[status] || 'info'
	})

	/**
	 * 支付状态文本
	 */
	const paymentStatusText = computed(() => {
		const status = orderData.value.paymentStatus
		const statusTexts = {
			0: '支付中',
			1: '已支付',
			2: '已退款'
		}
		return statusTexts[status] || '未知状态'
	})

	/**
	 * 订单状态操作按钮文本
	 */
	const orderStatusActionText = computed(() => {
		const status = orderData.value.orderStatus
		const actions = {
			1: '待支付',
			2: '已支付',
			3: '已完成',
			4: '已取消'
		}
		return actions[status] || '操作'
	})

	/**
	 * 检查是否有订单内容
	 */
	const hasOrderItems = computed(() => {
		return (orderData.value.products && orderData.value.products.length > 0) ||
			(orderData.value.courses) ||
			(orderData.value.rooms)
	})

	/**
	 * 获取订单详情
	 */
	const fetchOrderData = async () => {
		loading.value = true
		try {
			const res = await getOrderDetails(orderId.value)
			if (res.data) {
				orderData.value = res.data
			}
		} catch (error) {
			ElMessage.error('获取订单详情失败')
		} finally {
			loading.value = false
		}
	}

	// 获取订单数据
	onMounted(() => {
		fetchOrderData()
	})

	// 处理编辑
	const handleEdit = () => {
		router.push(`/order/edit/${orderId.value}`)
	}

	// 处理状态变更
	const handleStatusChange = () => {
		const status = orderData.value.orderStatus
		let action = ''
		let confirmMessage = ''
		let successMessage = ''
		let apiCall = null

		switch (status) {
			case 0: // 待支付 -> 取消订单（后台可以强制取消）
				action = '取消'
				confirmMessage = '确定要取消该订单吗？'
				successMessage = '订单已取消'
				apiCall = () => updateOrder({
					id: orderId.value,
					orderStatus: 3 // 已取消
				})
				break
			case 1: // 已支付待确认 -> 确认订单（后台确认）
				action = '确认'
				confirmMessage = '确定要确认该订单已完成吗？'
				successMessage = '订单已确认完成'
				apiCall = () => accomplishOrder(orderId.value)
				break
			case 2: // 已完成 -> 可添加后台操作如：标记退款、重新发货等
				action = '标记退款'
				confirmMessage = '确定要标记该订单为已退款吗？'
				successMessage = '订单已标记为已退款'
				apiCall = () => updateOrder({
					id: orderId.value,
					paymentStatus: 4 // 假设4是已退款状态
				})
				break
			case 3: // 已取消 -> 可添加后台操作如：恢复订单
				action = '恢复订单'
				confirmMessage = '确定要恢复该订单吗？订单将重新进入待支付状态'
				successMessage = '订单已恢复'
				apiCall = () => updateOrder({
					id: orderId.value,
					orderStatus: 0 // 恢复为待支付
				})
				break
			default:
				break
		}

		if (!action) {
			ElMessage.warning('当前订单状态不支持此操作')
			return
		}

		ElMessageBox.confirm(
			confirmMessage,
			`${action}订单`, {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(async () => {
			if (apiCall) {
				await apiCall()
				ElMessage.success(successMessage)
				// 重新获取数据
				fetchOrderData()
			}
		}).catch(() => {
			ElMessage.info('已取消操作')
		})
	}
</script>

<style scoped>
	.order-detail-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		min-height: 0;
		overflow-y: auto;
	}

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.order-title {
		font-size: 20px;
		font-weight: 600;
		color: #303133;
		margin: 0;
	}

	.action-buttons {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.amount-info {
		display: flex;
		gap: 24px;
	}

	.info-item {
		display: flex;
		flex-direction: column;
	}

	.info-label {
		font-size: 14px;
		color: #909399;
	}

	.info-value {
		font-size: 24px;
		font-weight: 600;
		color: #303133;
	}

	.price {
		color: #409eff;
	}

	.main-content {
		flex: 1;
		display: flex;
		gap: 20px;
		min-height: 0;
	}

	.left-content {
		flex: 2;
		min-width: 0;
	}

	.right-sidebar {
		flex: 1;
		position: relative;
		max-height: calc(100vh - 200px);
	}

	.card-header {
		font-size: 16px;
		font-weight: 600;
		color: #303133;
	}

	.order-info {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.info-row {
		display: flex;
		gap: 16px;
	}

	.info-col {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.system-info {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.items-title {
		font-size: 16px;
		font-weight: 600;
		color: #303133;
		margin-bottom: 12px;
	}

	.mt-4 {
		margin-top: 16px;
	}

	.mt-6 {
		margin-top: 24px;
	}

	.mb-6 {
		margin-bottom: 24px;
	}

	.product-info {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.product-image {
		width: 50px;
		height: 50px;
		border-radius: 4px;
	}

	.course-detail,
	.room-detail {
		border: 1px solid #ebeef5;
		border-radius: 4px;
		padding: 16px;
	}

	.course-header,
	.room-header {
		display: flex;
		gap: 16px;
	}

	.course-image,
	.room-image {
		width: 120px;
		height: 80px;
		border-radius: 4px;
	}

	.course-info,
	.room-info {
		flex: 1;
	}

	.course-info h5,
	.room-info h5 {
		margin: 0 0 8px 0;
		font-size: 16px;
		color: #303133;
	}

	.course-description,
	.room-description {
		margin: 0 0 12px 0;
		font-size: 14px;
		color: #606266;
		line-height: 1.5;
	}

	.course-meta,
	.room-meta {
		display: flex;
		gap: 16px;
		font-size: 13px;
		color: #909399;
	}

	.meta-item {
		display: flex;
		align-items: center;
		gap: 4px;
	}

	.course-price,
	.room-price {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		min-width: 120px;
	}

	.price-label {
		font-size: 14px;
		color: #909399;
	}

	.price-value {
		font-size: 20px;
		font-weight: 600;
		color: #f56c6c;
	}

	/* 响应式调整 */
	@media (max-width: 768px) {

		.course-header,
		.room-header {
			flex-direction: column;
		}

		.course-price,
		.room-price {
			align-items: flex-start;
			margin-top: 12px;
		}
	}
</style>